package com.gupao.javavip.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.TimeUnit;

public class CuratorDemo {
    private static final String CONNECTION_STR = "192.168.56.101:2181";

    private static CuratorFramework curatorFramework;

    public static void main(String[] args) throws Exception {
        curatorFramework = CuratorFrameworkFactory.builder().
                connectString(CONNECTION_STR).sessionTimeoutMs(5000).
                retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();

        curatorFramework.start(); //启动

        createData();
//        delData();
        getData();

        TimeUnit.SECONDS.sleep(20);
    }

    private static void createData() throws Exception {
//        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).
//                forPath("/data/program","test".getBytes());

        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).
                forPath("/data/program", "test".getBytes());
    }

    private static void getData() throws Exception {
        String s = new String(curatorFramework.getData().forPath("/data/program"));
        System.out.println(s);
    }

    private static void delData() throws Exception {
        curatorFramework.delete().deletingChildrenIfNeeded().forPath("/data");
    }
}
